package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.wx.api.WxUserApi;
import net.guerlab.smart.wx.api.feign.FeignWxUserApi;
import net.guerlab.smart.wx.core.domain.WxUserDTO;
import net.guerlab.smart.wx.core.exception.WxUserInvalidException;
import net.guerlab.smart.wx.core.searchparams.WxUserSearchParams;
import net.guerlab.spring.searchparams.SearchParamsUtils;
import net.guerlab.web.result.ListObject;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * @author guer
 */
@Configuration
@AutoConfigureAfter(WxUserApiLocalServiceAutoConfigure.class)
public class WxUserApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(WxUserApi.class)
    public WxUserApi wxUserApiFeignWrapper(FeignWxUserApi api) {
        return new WxUserApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class WxUserApiFeignWrapper implements WxUserApi {

        private final FeignWxUserApi api;

        @Override
        public WxUserDTO findOne(String appId, String openId) {
            return Optional.ofNullable(api.findOne(appId, openId).getData()).orElseThrow(WxUserInvalidException::new);
        }

        @Override
        public ListObject<WxUserDTO> findList(WxUserSearchParams searchParams) {
            Map<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findList(params).getData()).orElse(ListObject.empty());
        }

        @Override
        public List<WxUserDTO> findAll(WxUserSearchParams searchParams) {
            Map<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findAll(params).getData()).orElse(Collections.emptyList());
        }

        @Override
        public Map<String, WxUserDTO> findMap(Collection<String> openIds) {
            return Optional.ofNullable(api.findMap(openIds).getData()).orElse(Collections.emptyMap());
        }

        @Override
        public int findCount(WxUserSearchParams searchParams) {
            Map<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findCount(params).getData()).orElse(0);
        }
    }

}
